<template>
  <div id="SpaceManagePage">
    <a-card title="空间管理" class="card-container">
      <a-flex justify="end" style="margin-bottom: 16px">
        <a-space size="middle">
          <a-button type="primary" href="/add_space" target="_blank">+ 创建空间</a-button>
          <a-button type="primary" ghost href="/space_analyze?queryPublic=1" target="_blank">
            分析公共图库
          </a-button>
          <a-button type="primary" ghost href="/space_analyze?queryAll=1" target="_blank">
            分析全空间
          </a-button>
        </a-space>
      </a-flex>

      <!-- 搜索栏 -->
      <a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
        <a-form-item label="空间名称" name="spaceName" class="form-item">
          <a-input v-model:value="searchParams.spaceName" placeholder="请输入空间名称" allow-clear />
        </a-form-item>
        <a-form-item label="空间级别" name="spaceLevel" class="form-item">
          <a-select
            v-model:value="searchParams.spaceLevel"
            :options="SPACE_LEVEL_OPTIONS"
            placeholder="请选择空间级别"
            class="form-select"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="空间类别" name="spaceType" class="form-item">
          <a-select
            v-model:value="searchParams.spaceType"
            :options="SPACE_TYPE_OPTIONS"
            placeholder="请输入空间类别"
            class="form-select"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="用户 ID" name="userId" class="form-item">
          <a-input v-model:value="searchParams.userId" placeholder="请输入用户 ID" allow-clear />
        </a-form-item>
        <a-form-item class="form-item">
          <a-button type="primary" html-type="submit">
            <template #icon><SearchOutlined /></template>
            搜索
          </a-button>
        </a-form-item>
      </a-form>

      <!-- 表格列表 -->
      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="pagination"
        @change="doTabelChange"
        class="custom-table"
      >
        <template #bodyCell="{ column, record }">
          <!-- 空间级别 -->
          <template v-if="column.dataIndex === 'spaceLevel'">
            <a-tag>{{ SPACE_LEVEL_MAP[record.spaceLevel] }}</a-tag>
          </template>
          <!-- 空间类别 -->
          <template v-if="column.dataIndex === 'spaceType'">
            <a-tag>{{ SPACE_TYPE_MAP[record.spaceType] }}</a-tag>
          </template>
          <!-- 使用情况 -->
          <template v-if="column.dataIndex === 'spaceUseInfo'">
            <div>大小：{{ formatSize(record.totalSize) }} / {{ formatSize(record.maxSize) }}</div>
            <div>数量：{{ record.totalCount }} / {{ record.maxCount }}</div>
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-else-if="column.dataIndex === 'editTime'">
            {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space wrap>
              <!-- 编辑按钮 -->
              <a-button type="link" :href="`/add_space?id=${record.id}`" target="_blank">
                <template #icon><EditOutlined /></template>
                编辑
              </a-button>
              <!-- 分析按钮 -->
              <a-button type="link" :href="`/space_analyze?spaceId=${record.id}`" target="_blank">
                <template #icon><AreaChartOutlined /></template>
                分析
              </a-button>
              <!-- 删除按钮 -->
              <a-popconfirm
                title="确定要删除该空间吗？此操作不可逆！"
                ok-text="确认删除"
                cancel-text="取消"
                @confirm="doDelete(record.id)"
              >
                <a-button type="link" danger>
                  <template #icon><DeleteOutlined /></template>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import {
  deleteSpaceUsingPost,
  listSpaceByPageUsingPost
} from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  AreaChartOutlined,
  SearchOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import {
  SPACE_LEVEL_MAP,
  SPACE_LEVEL_OPTIONS,
  SPACE_TYPE_MAP,
  SPACE_TYPE_OPTIONS
} from '../../constants/space.ts'
import { formatSize } from '../../utils'
import "echarts";

const columns = [
  { title: 'ID', dataIndex: 'id', width: 80 },
  { title: '空间名称', dataIndex: 'spaceName' },
  { title: '空间级别', dataIndex: 'spaceLevel' },
  { title: '空间类别', dataIndex: 'spaceType' },
  { title: '使用情况', dataIndex: 'spaceUseInfo' },
  { title: '用户 ID', dataIndex: 'userId', width: 80 },
  { title: '创建时间', dataIndex: 'createTime' },
  { title: '编辑时间', dataIndex: 'editTime' },
  { title: '操作', key: 'action' },
]

const dataList = ref([])
const total = ref(0)

const searchParams = reactive<API.SpaceQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
})

const pagination = computed(() => ({
  current: searchParams.current ?? 1,
  pageSize: searchParams.pageSize ?? 10,
  total: total.value,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`,
}))

const fetchData = async () => {
  const res = await listSpaceByPageUsingPost({ ...searchParams })
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

onMounted(() => {
  fetchData()
})

const doSearch = () => {
  searchParams.current = 1
  fetchData()
}

const doTabelChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

const doDelete = async (id: string) => {
  if (!id) return
  const res = await deleteSpaceUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    fetchData()
  } else {
    message.error('删除失败')
  }
}
</script>

<style scoped>
#SpaceManagePage {
  background: linear-gradient(to bottom right, #f4f7fc, #eaeefb);
  min-height: 100vh;
  padding: 50px;
}

.card-container {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 12px 36px rgba(0, 0, 0, 0.1);
  padding: 20px;
  transition: transform 0.3s ease-in-out;
}

.card-container:hover {
  transform: translateY(-5px);
  box-shadow: 0 16px 40px rgba(0, 0, 0, 0.15);
}

/* 优化搜索框样式 */
.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px; /* 统一间距 */
  margin-bottom: 20px;
}

.search-form .form-item {
  /* 适当设置最小宽度，确保内容显示正常 */
  min-width: 220px;
}

.search-form .ant-input,
.search-form .ant-select {
  width: 100%;
}

/* 表格样式保持原有 */
.custom-table {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease-in-out;
}
.custom-table:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}
.ant-table-thead th {
  background: #f0f2f5;
  color: #333;
  font-weight: bold;
}
.ant-table-tbody td {
  color: #666;
}
.ant-table-tbody tr:hover {
  background: #f9fafc;
}
.ant-table-pagination.ant-pagination button {
  border-radius: 8px;
  transition: background-color 0.3s ease-in-out;
}
.ant-table-pagination.ant-pagination button:hover {
  background-color: #f0f2f5;
}
</style>
